import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from BeautifulSoup import BeautifulSoup
from xmw.tianya.bot import *

from xmw import tianya
import xmw
from xmw import error
import os
import urllib2, urllib
import uuid
import tianya
from google.appengine.ext import webapp


class MainPage(xmw.RequestHandler):


    def get_thread_by_url(self, url):
        q = tianya.Tianya_Thread.all()
        q.filter('lst_page_url = ', url)
        thread = q.get()
        return thread
        
    def get(self):
        """
        Step1:
            1.search INIT thread
            2.if not exist,search RUN Thread
            3.if not exist,search SYN Thread
        Step2:
            get thread info,and save it into db
        """
                
        (url,e)=self.get_key_from_GET("url")
        
        if e is not None:
            #e.log()
            self.render_error(e)
            return
        
        
        thread=self.get_thread_by_url(url)
        if thread is not None:
            template_values = { "thread":thread }
            self.render_template(template_values, '../template/thread.html')            
            return
        
        if thread is None:
            #new thread ..need to create it
            urls=[]
            urls.append(url)
            thread=tianya.Tianya_Thread(thread_id=xmw.get_uuid_hex(),lst_page_url=urls)
            thread=thread.refresh()
            #print "122"
            #now to refresh it
            if thread is not None:
                template_values = { "thread":thread }
                self.render_template(template_values, '../template/thread.html')
                return
            else:
                e=xmw.error.INVALIDE_THREAD_URL(url)
                self.render_error(e)
                return

    
def main():
    application = webapp.WSGIApplication(
                                       [('/tianya/get_thread_by_url', MainPage)],
                                       debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
